package com.qiyu.tech.pay.queue;

import com.alibaba.fastjson.JSON;
import com.qiyu.core.cache.redis.client.RedisService;
import com.qiyu.tech.pay.queue.model.DelayTaskSortItem;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import redis.clients.jedis.Tuple;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Set;

/**
 * @Author idea
 * @Date created in 9:01 上午 2021/3/30
 */
@Component("redisDelayQueue")
@Slf4j
public class RedisDelayQueue implements RedisQueue<DelayTaskSortItem> {

    @Resource
    private RedisService redisService;

    private static String redisDelayQueueKey = "redis:delay:pay:notify";

    private static final Object mutex = new Object();

    @Override
    public DelayTaskSortItem pop() {
        synchronized (mutex) {
            Set<Tuple> rangeSet = redisService.zRangeWithScores(redisDelayQueueKey, 0, 1);
            if (CollectionUtils.isEmpty(rangeSet)) {
                return null;
            }
            for (Tuple tuple : rangeSet) {
                long currentTimeMillis = System.currentTimeMillis();
                double expireTime = tuple.getScore();
                if ((currentTimeMillis - expireTime) > 0) {
                    DelayTaskSortItem delayTaskInfo = JSON.parseObject(tuple.getElement(), DelayTaskSortItem.class);
                    log.info("[delayTaskInfo] info is : {}", delayTaskInfo);
                    return delayTaskInfo;
                }
            }
        }
        return null;
    }

    @Override
    public boolean put(DelayTaskSortItem delayTaskSortItem) {
        redisService.zAdd(redisDelayQueueKey, delayTaskSortItem.getExecuteTime(), JSON.toJSONString(delayTaskSortItem));
        return true;
    }

    @Override
    public boolean delete(DelayTaskSortItem delayTaskSortItem) {
        redisService.zRem(redisDelayQueueKey, Arrays.asList(String.valueOf(JSON.toJSONString(delayTaskSortItem))));
        return true;
    }
}
